package com.sc.smartcommunity.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sc.smartcommunity.domain.Announcement;
import com.sc.smartcommunity.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 公告控制器（仅处理标题和内容）
 */
@RestController
@RequestMapping("/api/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 分页查询公告
     */
    @GetMapping
    public Map<String, Object> getAnnouncements(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String title) {

        Page<Announcement> page = new Page<>(pageNum, pageSize);
        IPage<Announcement> announcementPage = announcementService.getPage(page, title);

        Map<String, Object> result = new HashMap<>();
        result.put("total", announcementPage.getTotal());
        result.put("list", announcementPage.getRecords());
        result.put("pages", announcementPage.getPages());

        return result;
    }

    /**
     * 获取公告详情
     */
    @GetMapping("/{id}")
    public Announcement getAnnouncementDetail(@PathVariable Long id) {
        return announcementService.getByIdWithViewCount(id);
    }

    /**
     * 创建公告
     */
    @PostMapping("/add")
    public boolean createAnnouncement(@RequestBody Announcement announcement) {
        // 仅需要标题和内容
        return announcementService.save(announcement);
    }

    /**
     * 更新公告
     */
    @PutMapping("/update/{id}")
    public boolean updateAnnouncement(
            @PathVariable Long id,
            @RequestBody Announcement announcement) {
        announcement.setId(id);
        return announcementService.updateById(announcement);
    }

    /**
     * 删除公告
     */
    @DeleteMapping("/delete/{id}")
    public boolean deleteAnnouncement(@PathVariable Long id) {
        return announcementService.removeById(id);
    }
}
